<template>
  <div class="global-header">
    <div class="header-content">
      <div class="logo">
        <h1>智能学习辅助系统</h1>
      </div>
      <div class="user-info">
        <el-dropdown @command="handleCommand">
          <div class="avatar-container">
            <el-avatar
                :size="40"
                :src="avatar"
                :icon="User"
            />
            <span class="username">{{ username }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="logout" divided>
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { UserFilled, User, SwitchButton } from '@element-plus/icons-vue'

const router = useRouter()
let avatar;
avatar = ref(localStorage.getItem('avatar') || '用户')
const username = ref(localStorage.getItem('username') || '用户')

// 在组件挂载时获取用户信息
onMounted(async () => {
  if (localStorage.getItem('token')) {
    console.log('avatar:', localStorage.getItem('avatar'))
    avatar = ref(localStorage.getItem('avatar') || '用户')
  }
})

const handleCommand = async (command) => {
  switch (command) {
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        await router.push('/login')
      } catch {
        // 用户取消退出
      }
      break
  }
}
</script>

<style scoped>
.global-header {
  background-color: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  height: 60px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.logo h1 {
  margin: 0;
  font-size: 20px;
  color: var(--el-text-color-primary);
  font-weight: 600;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.avatar-container:hover {
  background-color: var(--el-fill-color-light);
}

.username {
  color: var(--el-text-color-primary);
  font-size: 14px;
}
</style> 